<template>
  <div style="width: calc(100vw); height: calc(100vh); display: flex; justify-content: space-between; ">
    <MonacoEditor class="w-full h-40" v-model="editorData" :disabled="disabled" :constModelData="constModelData" :eheight="eheight" style="width: calc(100vw);" :editorConfig="editorConfig" :minimap="true"></MonacoEditor>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, ref } from 'vue';
  import { getCurrentWindow } from '@tauri-apps/api/window';
  import MonacoEditor from '../components/monaco/index.vue'
  import { invoke } from '@tauri-apps/api/core';
  import { useDebounceEffect } from '../hooks/useDebounceEffect';
  import { useKeyboard } from '../components/useKeyboard';
  import { useMessage } from 'naive-ui';

  const message = useMessage()
  //json缓存文件
  const editorData = ref("");
  const disabled = ref(false);
  const constModelData = ref([""]);
  const eheight = ref("height: calc(100vh); width: calc(100vw);");
  const editorConfig = {
      language: "sql",
      theme: "vs-dark"
  };
  const app = getCurrentWindow();
  let id = "";
  let title = "";
  let heading = "";
  let date = "";
  //let group_type = "";
  let group_id = "";

  // 把 invoke 的逻辑放到这里
  useDebounceEffect(editorData, async (val) => {
    try {
      let data:any = await invoke("update", { id: id, noteContent: editorData.value, title: title, heading: heading, date: date, groupId: group_id });
      if (data.is_success) {
      }
      console.log('后台已更新为:', val)
    } catch (e) {
      console.error(`invoke 调用失败`, e)
    }
  }, 800)  // 800 ms 防抖

  onMounted(async () => {
    const label = app.label;
    const eid = label.replace("editor-", "");
    let data:any = await invoke("get_info_by_id", { id: eid });
    if (data.is_success) {
      editorData.value = data.data.note_content;
      id = data.data.id;
      title = data.data.title;
      heading = data.data.heading;
      date = data.data.date;
      //group_type = data.data.group_type;
      group_id = data.data.group_id;
    }
    await app.show();
    await app.setTitle(title + " - text");
  });


  // 监听 Ctrl + S 组合键
  useKeyboard('s', async (event) => {
      if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') {
          event.preventDefault(); // 阻止默认保存行为（特别是在 Web 中）
            try {
              let data:any = await invoke("update", { id: id, noteContent: editorData.value, title: title, heading: heading, date: date, groupId: group_id });
              if (data.is_success) {
                message.success(
                    '保存成功'
                )
              }
              
            } catch (e) {
              console.error(`invoke 调用失败`, e)
            }
      }
  });
  
</script>
